<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Category;
use App\Models\ProductVariant;
use App\Models\VariantAttribute;
use App\Models\SpecificationTemplate;
use App\Traits\LogsActivity;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AdminProductController extends Controller
{
    use LogsActivity;
    /**
     * 显示产品列表
     */
    public function index(Request $request): Response
    {
        $query = Product::with(['categories', 'variants']);

        // 搜索
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('sku', 'like', "%{$search}%");
            });
        }

        // 分类筛选
        if ($request->filled('category_id')) {
            $query->whereHas('categories', function ($q) use ($request) {
                $q->where('categories.id', $request->category_id);
            });
        }

        // 状态筛选
        if ($request->filled('is_active')) {
            $query->where('is_active', $request->is_active);
        }

        // 产品类型筛选
        if ($request->filled('product_type')) {
            $query->where('product_type', $request->product_type);
        }

        // 推荐状态筛选
        if ($request->filled('is_featured')) {
            $query->where('is_featured', $request->is_featured);
        }

        // 库存状态筛选
        if ($request->filled('stock_status')) {
            switch ($request->stock_status) {
                case 'normal':
                    $query->where('stock_quantity', '>', 10);
                    break;
                case 'low':
                    $query->whereBetween('stock_quantity', [1, 10]);
                    break;
                case 'out':
                    $query->where('stock_quantity', 0);
                    break;
            }
        }

        // 价格区间筛选
        if ($request->filled('price_min')) {
            $query->where('price', '>=', $request->price_min);
        }
        if ($request->filled('price_max')) {
            $query->where('price', '<=', $request->price_max);
        }

        $products = $query->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($product) {
                return [
                    'id' => $product->id,
                    'name' => $product->name,
                    'slug' => $product->slug,
                    'price' => $product->price,
                    'compare_price' => $product->compare_price,
                    'product_type' => $product->product_type,
                    'is_active' => $product->is_active,
                    'is_featured' => $product->is_featured,
                    'stock_quantity' => $product->stock_quantity,
                    'categories' => $product->categories->pluck('name')->toArray(),
                    'variants_count' => $product->variants->count(),
                    'created_at' => $product->created_at,
                    'updated_at' => $product->updated_at,
                ];
            });

        // 获取所有分类用于筛选
        $categories = Category::where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get(['id', 'name']);

        return Inertia::render('Admin/Products/Index', [
            'products' => $products,
            'categories' => $categories,
        ]);
    }

    /**
     * 显示创建产品表单
     */
    public function create(): Response
    {
        $categories = Category::where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get(['id', 'name']);

        $availableAttributes = VariantAttribute::where('is_variant', true)
            ->orderBy('sort_order', 'desc')
            ->orderBy('name')
            ->get()
            ->map(function ($attribute) {
                return [
                    'id' => $attribute->id,
                    'name' => $attribute->name,
                    'slug' => $attribute->slug,
                    'type' => $attribute->type,
                    'type_label' => $attribute->type_label,
                    'options' => $attribute->options,
                    'is_required' => $attribute->is_required,
                ];
            });

        // 获取规格模板
        $specificationTemplates = SpecificationTemplate::with(['category'])
            ->where('is_active', true)
            ->orderBy('sort_order', 'desc')
            ->orderBy('name')
            ->get()
            ->map(function ($template) {
                return [
                    'id' => $template->id,
                    'name' => $template->name,
                    'slug' => $template->slug,
                    'description' => $template->description,
                    'category_id' => $template->category_id,
                    'category_name' => $template->category ? $template->category->name : '全局模板',
                    'attributes_config' => $template->attributes_config,
                    'is_default' => $template->is_default,
                ];
            });

        return Inertia::render('Admin/Products/Create', [
            'categories' => $categories,
            'availableAttributes' => $availableAttributes,
            'specificationTemplates' => $specificationTemplates,
        ]);
    }
    /**
     * 存储新产品
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:products,slug',
            'sku' => 'required|string|max:255|unique:products,sku',
            'description' => 'nullable|string',
            'long_description' => 'nullable|string',
            'features' => 'nullable|array',
            'features.*' => 'nullable|string',
            'technical_specs' => 'nullable|array',
            'price' => 'required|numeric|min:0',
            'compare_price' => 'nullable|numeric|min:0',
            'product_type' => 'required|in:single,multi_variant',
            'is_active' => 'boolean',
            'is_featured' => 'boolean',
            'stock_quantity' => 'integer|min:0',
            'category_ids' => 'array',
            'category_ids.*' => 'exists:categories,id',
            'variants' => 'nullable|array',
            'variants.*.sku' => 'nullable|string|max:255',
            'variants.*.price' => 'required|numeric|min:0',
            'variants.*.stock_quantity' => 'nullable|integer|min:0',
            'variants.*.specifications' => 'required|array',
        ]);

        $isActive = $request->boolean('is_active', true);
        
        // 过滤空的特性
        $features = array_filter($request->features ?? [], function ($feature) {
            return !empty(trim($feature));
        });
        
        // 构建技术规格数据存储到 meta_data
        $metaData = [];
        if (!empty($request->technical_specs)) {
            $metaData['technical_specs'] = $request->technical_specs;
        }
        
        $product = Product::create([
            'name' => $request->name,
            'slug' => $request->slug,
            'sku' => $request->sku,
            'description' => $request->description,
            'long_description' => $request->long_description,
            'features' => array_values($features), // 重新索引数组
            'meta_data' => $metaData,
            'price' => $request->price,
            'compare_price' => $request->compare_price,
            'product_type' => $request->product_type,
            'is_active' => $isActive,
            'is_featured' => $request->boolean('is_featured', false),
            'stock_quantity' => $request->stock_quantity ?? 0,
            'published_at' => $isActive ? now() : null, // 如果启用则设置发布时间
        ]);

        // 关联分类
        if ($request->category_ids) {
            $product->categories()->sync($request->category_ids);
        }

        // 如果是多规格产品，创建变体
        if ($request->product_type === 'multi_variant' && $request->variants) {
            // 计算总库存（后端验证）
            $totalVariantStock = collect($request->variants)->sum('stock_quantity');
            
            foreach ($request->variants as $index => $variantData) {
                // 如果SKU为空，自动生成
                $sku = $variantData['sku'];
                if (empty($sku)) {
                    // 生成格式：产品SKU-变体序号
                    $sku = $product->sku . '-' . str_pad($index + 1, 2, '0', STR_PAD_LEFT);
                }
                
                // 生成变体名称（基于规格属性）
                $variantName = $product->name;
                if (!empty($variantData['specifications'])) {
                    $specNames = [];
                    foreach ($variantData['specifications'] as $spec) {
                        $specNames[] = $spec['value'];
                    }
                    if (!empty($specNames)) {
                        $variantName .= ' - ' . implode(' ', $specNames);
                    }
                }
                
                $variant = ProductVariant::create([
                    'product_id' => $product->id,
                    'name' => $variantName,
                    'sku' => $sku,
                    'price' => $variantData['price'],
                    'compare_price' => $variantData['compare_price'] ?? null,
                    'stock_quantity' => $variantData['stock_quantity'] ?? 0, // 默认为0
                    'is_active' => true,
                ]);

                // 创建变体属性值
                foreach ($variantData['specifications'] as $spec) {
                    \App\Models\VariantAttributeValue::create([
                        'variant_id' => $variant->id,
                        'attribute_id' => $spec['attribute_id'],
                        'value' => $spec['value'],
                        'display_value' => $spec['display_value'] ?: $spec['value'],
                    ]);
                }
            }
        }

        // 记录日志
        $this->logCreate(
            module: 'products',
            itemName: $product->name,
            model: $product
        );

        // 创建成功后跳转到编辑页，并带上锚点指向图片区域
        return redirect()->route('products.edit', $product->id)
            ->with('success', '产品创建成功！请上传产品图片')
            ->with('highlight_section', 'images');
    }

    /**
     * 显示编辑产品表单
     */
    public function edit(Product $product): Response
    {
        $product->load(['categories', 'variants.attributeValues.attribute', 'template']);
        
        $categories = Category::where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get(['id', 'name']);

        // 获取规格模板
        $specificationTemplates = SpecificationTemplate::with(['category'])
            ->where('is_active', true)
            ->orderBy('sort_order', 'desc')
            ->orderBy('name')
            ->get()
            ->map(function ($template) {
                return [
                    'id' => $template->id,
                    'name' => $template->name,
                    'slug' => $template->slug,
                    'description' => $template->description,
                    'category_id' => $template->category_id,
                    'category_name' => $template->category ? $template->category->name : '全局模板',
                    'attributes_config' => $template->attributes_config,
                    'is_default' => $template->is_default,
                ];
            });

        return Inertia::render('Admin/Products/Edit', [
            'product' => $product,
            'categories' => $categories,
            'specificationTemplates' => $specificationTemplates,
        ]);
    }

    /**
     * 更新产品
     */
    public function update(Request $request, Product $product)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'long_description' => 'nullable|string',
            'features' => 'nullable|array',
            'features.*' => 'nullable|string',
            'technical_specs' => 'nullable|array',
            'price' => 'required|numeric|min:0',
            'compare_price' => 'nullable|numeric|min:0',
            'is_active' => 'boolean',
            'is_featured' => 'boolean',
            'stock_quantity' => 'integer|min:0',
        ]);

        // 验证不可修改的字段没有被更改
        if ($request->has('slug') && $request->slug !== $product->slug) {
            return back()->withErrors(['slug' => '产品别名不可修改'])->withInput();
        }
        
        if ($request->has('sku') && $request->sku !== $product->sku) {
            return back()->withErrors(['sku' => '产品 SKU 不可修改'])->withInput();
        }
        
        if ($request->has('product_type') && $request->product_type !== $product->product_type) {
            return back()->withErrors(['product_type' => '产品类型不可修改'])->withInput();
        }
        
        if ($request->has('category_ids')) {
            $currentCategoryIds = $product->categories->pluck('id')->sort()->values()->toArray();
            $newCategoryIds = collect($request->category_ids)->sort()->values()->toArray();
            
            if ($currentCategoryIds !== $newCategoryIds) {
                return back()->withErrors(['category_ids' => '产品分类不可修改'])->withInput();
            }
        }

        $isActive = $request->boolean('is_active', true);
        $wasActive = $product->is_active;
        
        // 过滤空的特性
        $features = array_filter($request->features ?? [], function ($feature) {
            return !empty(trim($feature));
        });
        
        // 构建技术规格数据存储到 meta_data
        $metaData = $product->meta_data ?? [];
        if (!empty($request->technical_specs)) {
            $metaData['technical_specs'] = $request->technical_specs;
        } else {
            unset($metaData['technical_specs']);
        }
        
        // 只更新允许修改的字段
        $product->update([
            'name' => $request->name,
            'description' => $request->description,
            'long_description' => $request->long_description,
            'features' => array_values($features),
            'meta_data' => $metaData,
            'price' => $request->price,
            'compare_price' => $request->compare_price,
            'is_active' => $isActive,
            'is_featured' => $request->boolean('is_featured', false),
            'stock_quantity' => $request->stock_quantity ?? 0,
            'published_at' => $isActive && !$wasActive ? now() : $product->published_at,
        ]);

        // 分类不允许修改，所以不需要同步分类

        // 记录日志
        $this->logUpdate(
            module: 'products',
            itemName: $product->name,
            model: $product
        );

        return redirect()->route('products.index')
            ->with('success', '产品更新成功！');
    }

    /**
     * 删除产品
     */
    public function destroy(Product $product)
    {
        // 检查是否有订单关联
        if ($product->orderItems()->count() > 0) {
            return redirect()->route('products.index')
                ->with('error', '无法删除有订单记录的产品！');
        }

        $productName = $product->name;
        $product->delete();

        // 记录日志
        $this->logDelete(
            module: 'products',
            itemName: $productName,
            model: null // 模型已删除
        );

        return redirect()->route('products.index')
            ->with('success', '产品删除成功！');
    }

    /**
     * 切换产品状态
     */
    public function toggleStatus(Product $product)
    {
        $oldStatus = $product->is_active;
        $product->update([
            'is_active' => !$product->is_active,
        ]);
        
        $this->logToggleStatus(
            module: 'products',
            itemName: $product->name,
            status: $product->is_active ? '启用' : '禁用',
            model: $product
        );

        return redirect()->route('products.index')
            ->with('success', '产品状态更新成功！');
    }

    /**
     * 切换推荐状态
     */
    public function toggleFeatured(Product $product)
    {
        $product->update([
            'is_featured' => !$product->is_featured,
        ]);
        
        $this->logActivity(
            action: 'update',
            module: 'products',
            description: "切换产品推荐状态: {$product->name} -> " . ($product->is_featured ? '推荐' : '不推荐'),
            model: $product
        );

        return redirect()->route('products.index')
            ->with('success', '推荐状态更新成功！');
    }

    /**
     * 显示产品变体管理页面
     */
    public function variants(Product $product): Response
    {
        $variants = $product->variants()
            ->with(['attributeValues.attribute'])
            ->get()
            ->map(function ($variant) {
                return [
                    'id' => $variant->id,
                    'sku' => $variant->sku,
                    'price' => $variant->price,
                    'compare_price' => $variant->compare_price,
                    'stock_quantity' => $variant->stock_quantity,
                    'is_active' => $variant->is_active,
                    'specifications' => $variant->attributeValues->map(function ($value) {
                        return [
                            'id' => $value->id,
                            'attribute_id' => $value->attribute_id,
                            'attribute_name' => $value->attribute->name,
                            'attribute_type' => $value->attribute->type,
                            'attribute_options' => $value->attribute->options,
                            'value' => $value->value,
                            'display_value' => $value->display_value,
                        ];
                    }),
                ];
            });

        return Inertia::render('Admin/Products/Variants', [
            'product' => [
                'id' => $product->id,
                'name' => $product->name,
                'description' => $product->description,
                'price' => $product->price,
                'compare_price' => $product->compare_price,
                'is_active' => $product->is_active,
                'is_featured' => $product->is_featured,
                'images' => $product->images->map(function ($image) {
                    return [
                        'id' => $image->id,
                        'url' => $image->url,
                        'alt' => $image->alt,
                    ];
                }),
            ],
            'variants' => $variants,
        ]);
    }
}